package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.nurse.ActivityManager;
import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.beans.ArticleKindBean;
import com.hxkcloud.nurse.beans.DoctorGroupBean;
import com.hxkcloud.nurse.beans.HospitalStatusBean;
import com.hxkcloud.nurse.beans.MonitorKindBean;
import com.hxkcloud.nurse.beans.NurseMsgBean;
import com.hxkcloud.nurse.dborm.ArticleKindDao;
import com.hxkcloud.nurse.dborm.DoctorGroupDao;
import com.hxkcloud.nurse.dborm.HospitalStatusDao;
import com.hxkcloud.nurse.dborm.MonitorKindDao;
import com.hxkcloud.nurse.fragments.AssistantFragment;
import com.hxkcloud.nurse.fragments.BaseFragment;
import com.hxkcloud.nurse.fragments.DiscoverFragment;
import com.hxkcloud.nurse.fragments.MineFragment;
import com.hxkcloud.nurse.fragments.UserManagerFragment;
import com.hxkcloud.nurse.interfaces.IResponseNewMsgInfoListener;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.BadgeUtil;
import com.hxkcloud.nurse.utils.SharedPreferenceUtil;
import com.hxkcloud.nurse.views.MainViewPager;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-07-06.
 * Description:护士登录主页面
 */
public class NurseFragmentActivity extends BaseFragmentActivity implements View.OnClickListener {
    public MainViewPager viewPager;
    public List<BaseFragment> fragments = new ArrayList<BaseFragment>();
    private ImageView iv_discover, iv_manage, iv_assistant, iv_mine;
    private LinearLayout ll_discover, ll_manage, ll_assistant, ll_mine;
    private TextView tv_discover, tv_manage, tv_assistant, tv_mine;
    private FragmentManager fragmentManager;
    private int currIndex = 0;// 当前页卡编号
    private boolean getbasic = false;//是否需要获取文章类型，监测类型
    private List<ArticleKindBean> kinds_news;
    private List<ArticleKindBean> kinds_course;

    private DiscoverFragment discoverFragment;
    private UserManagerFragment userManagerFragment;
    private AssistantFragment assistantFragment;
    private MineFragment mineFragment;

    private boolean isMsg = false;//推送打开消息页
    private boolean isCourse = false;//推送打开课堂

    public static NurseFragmentActivity nurseFragmentActivity;
    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_MONITORKIND_SUCCESS:
                List<MonitorKindBean> kinds = (List<MonitorKindBean>) msg.obj;
                if (kinds != null && kinds.size() > 0) {
                    MonitorKindDao monitorKindDao = new MonitorKindDao(mContext);
                    monitorKindDao.setKind(kinds, "1");
                }
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS0:
                kinds_news = (List<ArticleKindBean>) msg.obj;
                if (kinds_course != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, "1");
                }
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS1:
                kinds_course = (List<ArticleKindBean>) msg.obj;
                if (kinds_news != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, "1");
                }
                break;
            case MessageCode.MSG_CHECKNEWMSG_HAVE:
                //  checkNurseNewMsg();
                break;
            case MessageCode.MSG_CHECKNEWMSG_HAVENOT:

                //   checkNurseNewMsg();
                break;
            case MessageCode.NETWORKCODE_GETDOCTORGROULIST_SUCCESS:
                List<DoctorGroupBean> groups = (List<DoctorGroupBean>) msg.obj;
                if (groups != null && groups.size() > 0) {
                    DoctorGroupDao doctorGroupDao = new DoctorGroupDao(mContext);
                    doctorGroupDao.setGroup(groups);
                }
                discoverFragment.setDoctorGroup(groups);
                break;
            case MessageCode.NETWORKCODE_HOSPITALSTATUSLIST_SUCCESS:
                Log.i("=====>","NurseFragment");
                List<HospitalStatusBean> hss = (List<HospitalStatusBean>) msg.obj;
                HospitalStatusDao hsDao = new HospitalStatusDao(mContext);
                hsDao.setHospitalStatus(hss);
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        YjhApplication.getInstance().unregisterListener();
        setContentView(R.layout.activity_nursemain);
        currIndex = getIntent().getIntExtra("index", 0);
        getbasic = getIntent().getBooleanExtra("getbasic", false);
        isMsg = getIntent().getBooleanExtra("msg", false);
        isCourse = getIntent().getBooleanExtra("course", false);
        initViews();

        if (getbasic) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    YiJiaHuNetWorkUtils.getMonitorKind(loginInfo.getDepartmentId(), handler);
                    YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_news, handler);//type两个都取|加入科室后重取
                    YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_course, handler);
                    YiJiaHuNetWorkUtils.getDoctorGroupList(loginInfo.getDepartmentId(), handler);
                    YiJiaHuNetWorkUtils.getHospitalStatusList(handler);
                }
            }, 200);
        }
        getNewMsg();

        if (isMsg) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent iM = new Intent(mContext, MessageMainActivity.class);
                    startActivity(iM);
                }
            }, 500);
        } else if (isCourse) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent courseIntent = new Intent(mContext, NewsActivity.class);
                    courseIntent.putExtra("type", YjhApplication.articlekind_course);
                    startActivity(courseIntent);
                }
            }, 500);
        } else {
            // [170515] hum modify: 已经把检测更新放到了StartActivity
            // judgeUpdate();
        }
        nurseFragmentActivity = this;

        // checkNurseNewMsg();
    }


    //监测是否有新的消息
    @Override
    public void checkNurseNewMsg() {
        YiJiaHuNetWorkUtils.checkNurseNewMsg(new IResponseNewMsgInfoListener() {
            @Override
            public void responseInfo(Object object) {
                int num = 0;
                if (object != null) {
                    NurseMsgBean nurseMsgBean = (NurseMsgBean) object;
                    num = nurseMsgBean.getAssessNurse() + nurseMsgBean.getMinitor() + nurseMsgBean.getSystem();
                    if (num > 0) {
                        discoverFragment.showPoint(true);
                        userManagerFragment.showPoint(true, jpushType);
                        assistantFragment.showPoint(true);
                        mineFragment.showPoint(true);
                    } else {
                        discoverFragment.showPoint(false);
                        userManagerFragment.showPoint(false, jpushType);
                        assistantFragment.showPoint(false);
                        mineFragment.showPoint(false);
                    }
                }
                num += YjhApplication.getInstance().getMsgNum();
                BadgeUtil.setBadgeCount(NurseFragmentActivity.this, num);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Message msg = handler.obtainMessage(MessageCode.MSG_CHECKNEWMSG);
        msg.sendToTarget();
        checkNurseNewMsg();
    }

    private void initViews() {
        viewPager = (MainViewPager) findViewById(R.id.viewPager_nurse);
        iv_manage = (ImageView) findViewById(R.id.iv_nursemain_manage);
        iv_assistant = (ImageView) findViewById(R.id.iv_nursemain_assistant);
        iv_discover = (ImageView) findViewById(R.id.iv_nursemain_discover);
        iv_mine = (ImageView) findViewById(R.id.iv_nursemain_mine);
        ll_manage = (LinearLayout) findViewById(R.id.ll_nursemain_manage);
        ll_assistant = (LinearLayout) findViewById(R.id.ll_nursemain_assistant);
        ll_discover = (LinearLayout) findViewById(R.id.ll_nursemain_discover);
        ll_mine = (LinearLayout) findViewById(R.id.ll_nursemain_mine);
        tv_manage = (TextView) findViewById(R.id.tv_nursemain_manage);
        tv_assistant = (TextView) findViewById(R.id.tv_nursemain_assistant);
        tv_discover = (TextView) findViewById(R.id.tv_nursemain_discover);
        tv_mine = (TextView) findViewById(R.id.tv_nursemain_mine);

        discoverFragment = DiscoverFragment.newInstance();
        userManagerFragment = UserManagerFragment.newInstance();
        assistantFragment = AssistantFragment.newInstance();
        mineFragment =  MineFragment.newInstance();
        fragments.add(discoverFragment);
        fragments.add(userManagerFragment);
        fragments.add(assistantFragment);
        fragments.add(mineFragment);

        fragmentManager = this.getSupportFragmentManager();

        viewPager.setSlipping(true);//设置ViewPager是否可以滑动
        viewPager.setOffscreenPageLimit(0);
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setCurrentItem(currIndex);
        if (currIndex == 3) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((MineFragment) fragments.get(3)).gotoRZ();
                }
            }, 200);

        }

        ll_manage.setOnClickListener(this);
        ll_assistant.setOnClickListener(this);
        ll_discover.setOnClickListener(this);
        ll_mine.setOnClickListener(this);

        LinearLayout.LayoutParams lp_bottom1 = new LinearLayout.LayoutParams((screenWidth / 15) - 5, (screenWidth / 15) - 5);
        LinearLayout.LayoutParams lp_bottom2 = new LinearLayout.LayoutParams((screenWidth / 10) - 7, (screenWidth / 15) - 5);
        iv_discover.setLayoutParams(lp_bottom1);
        iv_manage.setLayoutParams(lp_bottom2);
        iv_assistant.setLayoutParams(lp_bottom1);
        iv_mine.setLayoutParams(lp_bottom1);
    }



    @Override
    public void onClick(View v) {
        if (fragments.size() != 4)
            return;
        switch (v.getId()) {
            case R.id.ll_nursemain_discover:
                if (currIndex!=0)
                    viewPager.setCurrentItem(0);
                break;
            case R.id.ll_nursemain_manage:
                if (currIndex!=1)
                    viewPager.setCurrentItem(1);
                break;
            case R.id.ll_nursemain_assistant:
                //if (fragments.get(2).isViewCreated())
                if (currIndex!=2)
                    viewPager.setCurrentItem(2);
                break;
            case R.id.ll_nursemain_mine:
                //if (fragments.get(3).isViewCreated())
                if (currIndex!=3)
                    viewPager.setCurrentItem(3);
                break;
        }
    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    iv_discover.setImageResource(R.drawable.tab_discover_pre);
                    iv_manage.setImageResource(R.drawable.tab_manage);
                    iv_assistant.setImageResource(R.drawable.tab_assistant);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_assistant.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;
                case 1:
                    iv_discover.setImageResource(R.drawable.tab_discover);
                    iv_manage.setImageResource(R.drawable.tab_manage_pre);
                    iv_assistant.setImageResource(R.drawable.tab_assistant);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_assistant.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));

                    if(null != userManagerFragment)
                    {
                        userManagerFragment.setAllAdapterDao();

                    }

                    break;
                case 2:
                    iv_discover.setImageResource(R.drawable.tab_discover);
                    iv_manage.setImageResource(R.drawable.tab_manage);
                    iv_assistant.setImageResource(R.drawable.tab_assistant_pre);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_assistant.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;
                case 3:
                    iv_discover.setImageResource(R.drawable.tab_discover);
                    iv_manage.setImageResource(R.drawable.tab_manage);
                    iv_assistant.setImageResource(R.drawable.tab_assistant);
                    iv_mine.setImageResource(R.drawable.tab_my_pre);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_assistant.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                  //  SendMsgUtils.sendAtMessage("测试","ejh18521092708",loginInfo.getName(), loginInfo.getHeadImg());
                    break;
                default:
                    break;
            }
            currIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

//        @Override
//        public void destroyItem(View container, int position, Object object) {
//            ((ViewPager) container).removeView(fragments.get(position).getView());
//        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            ((ViewPager) container).removeView(fragments.get(position).getView());
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = fragments.get(position);
            if (!fragment.isAdded()) { // 如果fragment还没有added
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(fragment, fragment.getClass().getSimpleName());
                ft.commit();
                /**
                 * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
                 * 会在进程的主线程中,用异步的方式来执行。
                 * 如果想要立即执行这个等待中的操作,就要调用这个方法(只能在主线程中调用)。
                 * 要注意的是,所有的回调和相关的行为都会在这个调用中被执行完成,因此要仔细确认这个方法的调用位置。
                 */
                fragmentManager.executePendingTransactions();
            }

            if (fragment.getView().getParent() == null) {
                container.addView(fragment.getView()); // 为viewpager增加布局
            }
            return fragment.getView();
        }

    }

    private long exitTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                toastMsg(R.string.doubleback);
                exitTime = System.currentTimeMillis();
            } else {
                cancelToast();
                SharedPreferenceUtil.setIsrunning(mContext, false);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        finish();
                        ActivityManager.getInstance().removeAllActivity();
                        System.exit(0);
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 200);
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    public static NurseFragmentActivity getInstance() {
        return nurseFragmentActivity;
    }

    private String jpushType = "";

    public void jpushNew(String type) {
        jpushType = type;
        handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
        checkNurseNewMsg();
    }

    public void jpushRefreshPatients() {
        userManagerFragment.jpushRefreshPatients();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        YjhApplication.getInstance().registerListener();
    }
}
